import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { ActionReducerMapBuilder, AsyncThunk } from "@reduxjs/toolkit";
import type { Order, OrderParams, OrderStatus, SettleAccounts, SettleAccountsParams } from "@/type/OrderType";
import type { AsyncThunkConfig } from "@reduxjs/toolkit/dist/createAsyncThunk";
import { cancelOrderAPI, fetchOrderListAPI, fetchOrderStatusAPI, paymentOrderAPI, settleAccountsInfoAPI, submitOrderAPI } from "@/api/orderAPI";

type CancelOrderAction = {
   type: string
   payload: number
}
type DeleteOrderAction = {
   type: string
   payload: number
}

type InitialState = {
   orderList: Order[],
   orderStatus: OrderStatus,
   checkoutDetail: any
}

const initialState: InitialState = {
   orderList: [],
   orderStatus: {} as OrderStatus,
   checkoutDetail: {},
};

/**
 * @description 获取订单列表的AsyncThunk函数
 * */
export const fetchOrderListThunk: AsyncThunk<Order[], OrderParams, AsyncThunkConfig> = createAsyncThunk("fetchOrderListThunk", async (orderParams, { rejectWithValue }) => {
   try {
      const { data: { list: { data } } } = await fetchOrderListAPI(orderParams);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});
/**
 * @description 获取订单状态的AsyncThunk函数
 * */
export const fetchOrderStatusThunk = createAsyncThunk("fetchOrderStatusThunk", async (_, { rejectWithValue }) => {
   try {
      const { data: { counts } } = await fetchOrderStatusAPI();
      return counts;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 取消订单的AsyncThunk函数
 * */
export const cancelOrderThunk: AsyncThunk<"取消成功", number, AsyncThunkConfig> = createAsyncThunk("cancelOrderThunk", async (orderId, { rejectWithValue, dispatch }) => {
   try {
      await cancelOrderAPI(orderId);
      dispatch(orderStore.actions.cancelOrder(orderId));
      return "取消成功";
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 获取订单结算信息的AsyncThunk函数
 * */
export const settleAccountsInfoThunk: AsyncThunk<SettleAccounts, SettleAccountsParams, AsyncThunkConfig> = createAsyncThunk("settleAccountsInfo", async (params, { rejectWithValue }) => {
   try {
      const { data } = await settleAccountsInfoAPI(params);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 提交订单的AsyncThunk函数
 * */
export const submitOrderThunk: AsyncThunk<SettleAccounts, SettleAccountsParams & { remark?: string, payType?: string }, AsyncThunkConfig> = createAsyncThunk("submitOrderThunk", async (params, { rejectWithValue }) => {
   try {
      const { data } = await submitOrderAPI(params);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 支付订单的AsyncThunk函数
 * */
export const paymentOrderThunk: AsyncThunk<string[], { orderId: string, payType: string }, AsyncThunkConfig> = createAsyncThunk("paymentOrderThunk", async (params, { rejectWithValue }) => {
   try {
      const { data } = await paymentOrderAPI(params);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

const orderStore = createSlice({
   name: "orderStore",
   initialState,
   reducers: {
      cancelOrder(state: InitialState, action: CancelOrderAction) {
         const order = state.orderList.find(item => item.order_id === action.payload) as Order;
         order.order_status = 21;
      },
      deleteOrder(state: InitialState, action: DeleteOrderAction) {
         state.orderList = state.orderList.filter(item => item.order_id !== action.payload);
      },
   },
   extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
      builder.addCase(fetchOrderListThunk.fulfilled, (state: InitialState, action: PayloadAction<Order[]>) => {
         state.orderList = action.payload;
      });
      builder.addCase(fetchOrderStatusThunk.fulfilled, (state: InitialState, action: PayloadAction<OrderStatus>) => {
         state.orderStatus = action.payload;
      });
      builder.addCase(settleAccountsInfoThunk.fulfilled, (state: InitialState, action: PayloadAction<any>) => {
         state.checkoutDetail = action.payload;
      });
   },
});
export const { cancelOrder, deleteOrder } = orderStore.actions;
export default orderStore.reducer;
